<template>
  <div class="trace-query-container">
    <div class="trace-header">
      <div class="logo">
        <img src="@/assets/logo.png" alt="宁夏枸杞农产品溯源系统" />
        <h1>商品防伪网站</h1>
      </div>
      <div class="nav-links">
        <!--        <router-link to="/">首页</router-link>-->
        <router-link to="/login">登录</router-link>
        <router-link to="/register">注册</router-link>
      </div>
    </div>

    <div class="trace-content">
      <div class="query-box" v-if="!productInfo">
        <h2>产品溯源查询</h2>
        <p class="query-desc">输入产品溯源码或者扫描二维码，查询产品溯源信息</p>

        <div class="query-input">
          <el-input
              v-model="traceCode"
              placeholder="请输入产品溯源码"
              clearable
              @keyup.enter="queryTrace">
            <template #append>
              <el-button icon="el-icon-search" @click="queryTrace" :loading="loading"></el-button>
            </template>
          </el-input>
        </div>

        <div class="query-actions">
          <el-button type="primary" @click="queryTrace" :loading="loading">查询</el-button>
          <el-button @click="generateQRCode" :disabled="!traceCode">生成二维码</el-button>
        </div>

        <!-- 在查询框下方直接显示二维码区域 -->
        <div class="qr-code-section" v-if="traceCode">
          <h3>产品溯源二维码</h3>
          <div class="qr-code-container-inline">
            <div v-if="qrCodeLoading" class="qr-loading">
              <i class="el-icon-loading"></i>
              <p>二维码生成中...</p>
            </div>
            <div v-else-if="qrCodeDataUrl" class="qr-result-inline">
              <img
                  :src="qrCodeDataUrl"
                  class="qr-image"
                  alt="产品溯源二维码" />
              <p class="qr-tip">
                <i class="el-icon-mobile-phone" style="margin-right: 5px;"></i>
                扫描二维码获取产品溯源信息，无网络也可查看
              </p>
              <el-button type="primary" size="small" @click="downloadQRCode" icon="el-icon-download">
                下载二维码
              </el-button>
            </div>
          </div>
        </div>

        <div class="query-tips">
          <p>温馨提示：</p>
          <ul>
            <li>溯源码一般印制在产品包装上或随附的溯源卡上</li>
            <li>溯源码区分大小写，请准确输入</li>
            <li>您也可以扫描产品包装上的二维码直接查询</li>
          </ul>
        </div>
      </div>

      <!-- 产品信息展示区域 -->
      <div class="product-info" v-if="productInfo" v-loading="detailsLoading">
        <div class="product-header">
          <h2>产品溯源信息</h2>
          <h3>{{frequency}}</h3>
          <el-button type="text" icon="el-icon-back" @click="resetQuery">返回查询</el-button>
        </div>

        <el-tabs v-model="activeTab">
          <el-tab-pane label="生产信息" name="basic">
            <div class="info-card">
              <div class="product-image">
                <img :src="productInfo.productImage || require('@/assets/logo.png')" alt="产品图片" />
              </div>
              <div class="product-details">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="显示名称">{{ products.productName }}</el-descriptions-item>

                  <el-descriptions-item label="批次">{{ products.batchNumber }}</el-descriptions-item>
                  <el-descriptions-item label="厂家名称">{{ products.storageMethods}}</el-descriptions-item>
                  <el-descriptions-item label="产地">{{ products.productionStandard }}</el-descriptions-item>
                  <el-descriptions-item label="生产日期">{{ products.plantingDate }}</el-descriptions-item>
                </el-descriptions>

                <div class="authenticity-seal" v-if="productInfo.verified">
                  <div class="seal-icon">
                    <i class="el-icon-check"></i>
                  </div>
                  <div class="seal-text">
                    <h4>溯源认证</h4>
                    <p>此产品信息已通过区块链认证，真实可靠</p>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="销售信息" name="planting">
            <div class="info-card">
              <el-descriptions :column="2" border>
                <!--                <el-descriptions-item label="种植户">{{ farmingInfo.farmerName }}</el-descriptions-item>-->
                <el-descriptions-item label="自销/经销">{{ orders.sales }}</el-descriptions-item>
                <el-descriptions-item label="商家名称">{{ orders.customerName}}</el-descriptions-item>
                <!--                <el-descriptions-item label="种植面积">{{ farmingInfo.plantingArea }}亩</el-descriptions-item>-->
                <!--                <el-descriptions-item label="种植日期">{{ farmingInfo.plantingDate }}</el-descriptions-item>-->
                <!--                <el-descriptions-item label="采收日期">{{ farmingInfo.harvestDate }}</el-descriptions-item>-->
                <el-descriptions-item label="商家地址" :span="2">{{ orders.location }}</el-descriptions-item>
                <el-descriptions-item label="联系方式" :span="2">{{ orders.customerPhone }}</el-descriptions-item>
              </el-descriptions>

              <div class="farm-images" v-if="farmingInfo.farmImages && farmingInfo.farmImages.length > 0">
                <h4>农场实景</h4>
                <div class="image-grid">
                  <div class="farm-image" v-for="(image, index) in farmingInfo.farmImages" :key="index">
                    <el-image
                        :src="image.url"
                        :preview-src-list="farmingInfo.farmImages.map(img => img.url)">
                    </el-image>
                    <div class="image-caption">{{ image.caption }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!--          <el-tab-pane label="加工信息" name="processing">-->
          <!--            <div class="info-card">-->
          <!--              <el-descriptions :column="2" border>-->
          <!--                <el-descriptions-item label="加工厂">{{ processingInfo.processingFactory }}</el-descriptions-item>-->
          <!--                <el-descriptions-item label="加工地址">{{ processingInfo.processingAddress }}</el-descriptions-item>-->
          <!--                <el-descriptions-item label="加工日期">{{ processingInfo.processingDate }}</el-descriptions-item>-->
          <!--                <el-descriptions-item label="包装日期">{{ processingInfo.packagingDate }}</el-descriptions-item>-->
          <!--                <el-descriptions-item label="保质期">{{ processingInfo.shelfLife }}</el-descriptions-item>-->
          <!--                <el-descriptions-item label="存储方式">{{ processingInfo.storageMethods }}</el-descriptions-item>-->
          <!--                <el-descriptions-item label="加工工艺" :span="2">{{ processingInfo.processingTechnology }}</el-descriptions-item>-->
          <!--                <el-descriptions-item label="检验报告" :span="2" v-if="processingInfo.inspectionReportUrl">-->
          <!--                  <el-link type="primary" :href="processingInfo.inspectionReportUrl" target="_blank">-->
          <!--                    <i class="el-icon-document"></i> 查看检验报告-->
          <!--                  </el-link>-->
          <!--                </el-descriptions-item>-->
          <!--              </el-descriptions>-->

          <!--              <div class="processing-steps" v-if="processingInfo.processingSteps && processingInfo.processingSteps.length > 0">-->
          <!--                <h4>加工流程</h4>-->
          <!--                <el-steps :active="processingInfo.processingSteps.length" direction="vertical">-->
          <!--                  <el-step-->
          <!--                    v-for="(step, index) in processingInfo.processingSteps"-->
          <!--                    :key="index"-->
          <!--                    :title="step.name"-->
          <!--                    :description="step.description">-->
          <!--                  </el-step>-->
          <!--                </el-steps>-->
          <!--              </div>-->
          <!--            </div>-->
          <!--          </el-tab-pane>-->

          <el-tab-pane label="物流信息" name="logistics">
            <div class="info-card">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="物流公司">{{ distributionInfo.logisticsCompany }}</el-descriptions-item>
                <el-descriptions-item label="物流订单">{{ distributionInfo.logisticsNumber }}</el-descriptions-item>
                <!--                <el-descriptions-item label="发货日期">{{ distributionInfo.shipDate }}</el-descriptions-item>-->
                <el-descriptions-item label="发货日期">{{ distributionInfo.shipDate }}</el-descriptions-item>
                <el-descriptions-item label="发货地址">{{ distributionInfo.startLocation }}</el-descriptions-item>
                <el-descriptions-item label="收货地址">{{ distributionInfo.toLocation }}</el-descriptions-item>
              </el-descriptions>

              <div class="logistics-track" v-if="distributionInfo.logisticsTrack && distributionInfo.logisticsTrack.length > 0">
                <h4>物流跟踪</h4>
                <el-timeline>
                  <el-timeline-item
                      v-for="(track, index) in distributionInfo.logisticsTrack"
                      :key="index"
                      :timestamp="track.time"
                      :color="index === 0 ? '#0bbd87' : ''"
                      :icon="index === 0 ? 'el-icon-check' : ''">
                    {{ track.location }} - {{ track.description }}
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div class="share-box">
          <h4>分享产品溯源信息</h4>
          <div class="share-buttons">
            <el-button type="primary" icon="el-icon-share" circle @click="shareProduct"></el-button>
            <el-button type="success" icon="el-icon-s-promotion" circle @click="shareProduct"></el-button>
            <el-button type="warning" icon="el-icon-star-off" circle @click="favoriteProduct"></el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="trace-footer">
      <p>© {{ new Date().getFullYear() }} 宁夏枸杞农产品溯源系统 版权所有</p>
      <p>技术支持: 宁夏枸杞科技有限公司</p>
    </div>

    <!-- 扫码对话框 -->
    <el-dialog title="扫描二维码" v-model:visible="scanDialogVisible" width="300px" center>
      <div class="scan-box">
        <div class="scan-area" ref="scanArea">
          <!-- 实际项目中应该集成扫码SDK -->
          <div class="scan-placeholder" v-if="!scannerInitialized">
            <i class="el-icon-loading"></i>
            <p>相机加载中...</p>
          </div>
          <div id="scanner-container" v-else></div>
        </div>
        <p class="scan-tip">请将二维码放入框内，系统将自动识别</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeScanDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生成的二维码对话框 -->
    <el-dialog
        title="产品溯源二维码"
        v-model:visible="qrDialogVisible"
        width="350px"
        center
        destroy-on-close>
      <div class="qr-code-container">
        <div v-if="qrCodeLoading" class="qr-loading">
          <i class="el-icon-loading"></i>
          <p>二维码生成中...</p>
        </div>
        <div v-else class="qr-result">
          <!-- 强制显示固定尺寸的图片 -->
          <img
              v-if="qrCodeDataUrl"
              :src="qrCodeDataUrl"
              class="qr-image"
              alt="产品溯源二维码" />
          <div v-else class="qr-error">
            <i class="el-icon-warning-outline"></i>
            <p>二维码生成失败</p>
          </div>
          <p class="qr-tip">
            <i class="el-icon-mobile-phone" style="margin-right: 5px;"></i>
            扫描二维码获取产品溯源信息，无网络也可查看
          </p>
          <div class="qr-actions">
            <el-button type="primary" size="small" @click="downloadQRCode" icon="el-icon-download" :disabled="!qrCodeDataUrl">
              下载二维码
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {distributionAPI, farmingAPI, productAPI, traceQueryAPI} from '@/api/api';
import QRCode from 'qrcode';

export default {
  name: 'TraceQueryView',
  data() {
    return {
      frequency:'',
      products:'',
      farmingDetails:'',
      traceCode: '',
      scanDialogVisible: false,
      qrDialogVisible: false,
      qrCodeLoading: false,
      loading: false,
      detailsLoading: false,
      productInfo: null,
      farmingInfo: {},
      orders:{},
      processingInfo: {},
      distributionInfo: {},
      activeTab: 'basic',
      scanner: null,
      scannerInitialized: false,
      qrCodeDataUrl: null,
      qrCodeGenerated: false,
      qrCodeInfo: null
    };
  },
  created() {
    // 检查URL中是否有traceCode参数
    const traceCode = this.$route.query.code;
    if (traceCode) {
      this.traceCode = traceCode;
      this.queryTrace();
    }

    // 尝试从本地存储恢复二维码数据
    this.restoreQrCodeFromStorage();
  },
  methods: {
    formatDate(dateArray) {
      return `${dateArray[0]}年${dateArray[1]}月${dateArray[2]}日`;
    },
    // 查询溯源信息
    async queryTrace() {
      if (!this.traceCode) {
        this.$message.warning('请输入溯源码');
        return;
      }

      this.loading = true;
      try {
        // 调用真实的API
        const response = await traceQueryAPI.queryTrace(this.traceCode);


        console.log(response)
        if (!response || response.code !== 200) {
          throw new Error(response?.message || '未找到相关产品信息');
        }

        // 设置产品信息
        const responseData = response.data;
        this.frequency=responseData.frequency
        if(responseData.orders){
          this.orders=responseData.orders
        }
        if(responseData.products){
          this.products=responseData.products
          this.products.plantingDate=this.formatDate(this.products.plantingDate)
        }
        // 确保将来自后端的数据正确映射到前端组件所需的格式
        this.productInfo = {
          ...responseData,
          productName: responseData.productName || '未知产品',
          productCode: responseData.productCode || '',
          batchNumber: responseData.batchNumber || '未知批次',
          origin: responseData.origin || '未知产地',
          qualityLevel: responseData.qualityLevel || '特级',
          productionStandard: responseData.productionStandard || 'GB/T 19330-2013',
          verified: responseData.verified !== false,
          productImage: responseData.productImage || require('@/assets/logo.png'),
        };

        // 如果已有种植信息，直接处理
        if (responseData.farmingInfo) {
          this.farmingInfo = {
            farmerName: responseData.farmingInfo.user?.username || '',
            farmName: responseData.farmingDetails?.farmer,
            plantingAddress: responseData.farmingInfo.location || '',
            plantingArea: responseData.farmingInfo.plantingArea || '0',
            plantingDate: responseData.farmingInfo.plantingDate || '',
            harvestDate: responseData.farmingInfo.harvestDate || '',
            fertilizerUsed: responseData.farmingInfo.fertilizer || '有机肥',
            pesticideUsed: responseData.farmingInfo.pesticide || '无农药'
          };
        }
        if(responseData.distributionInfo){
          this.distributionInfo=responseData.distributionInfo
          this.distributionInfo.shipDate=this.formatDate(this.distributionInfo.shipDate)
        }

        // 如果有完整的流通信息，直接处理
        // if (responseData.distributionInfo) {
        //   if (Array.isArray(responseData.distributionInfo)) {
        //     // 处理数组格式
        //     const latestDistribution = responseData.distributionInfo[0] || {};
        //     this.distributionInfo = this.formatDistributionInfo(latestDistribution);
        //   } else {
        //     // 处理对象格式
        //     this.distributionInfo = this.formatDistributionInfo(responseData.distributionInfo);
        //   }
        // }

        // 如果有步骤信息，保存起来
        if (responseData.steps && responseData.steps.length > 0) {
          this.productSteps = responseData.steps;
        }

        // 记录查询
        this.recordQuery();

        // 如果API返回的数据不全，获取更多详细信息
        if (!responseData.farmingInfo || !responseData.distributionInfo) {
          this.getDetailInfo();
        } else {
          this.detailsLoading = false;
        }
      } catch (error) {
        console.error('Failed to query trace info:', error);
        this.$message.error(`当前溯源码不存在: ${error.message || '服务器错误，请稍后再试'}`);
        this.productInfo = null;
      } finally {
        this.loading = false;
      }
    },

    // 辅助方法：格式化流通信息
    formatDistributionInfo(info) {
      return {
        logisticsCompany: info.logisticsCompany || '自营物流',
        logisticsNumber: info.logisticsNumber || '',
        shipDate: info.distributionDate || '',
        deliveryMethod: info.transportType || '公路运输',
        startLocation: info.fromLocation || '',
        destination: info.toLocation || '',
        logisticsTrack: info.trackingInfo || []
      };
    },

    // 记录溯源查询
    async recordQuery() {
      try {
        const queryData = {
          traceCode: this.traceCode,
          productId: this.productInfo.id,
          queryIp: '',
          queryDevice: navigator.userAgent,
          queryLocation: ''
        };

        // 记录查询日志
        await traceQueryAPI.recordQuery(queryData);
      } catch (logError) {
        console.error('Failed to record query log:', logError);
        // 不影响主流程，仅记录错误
      }
    },

    // 获取详细信息
    async getDetailInfo() {
      this.detailsLoading = true;
      try {
        // 获取种植信息
        if (this.productInfo.farmingInfoId) {
          const farmingResponse = await farmingAPI.getFarmingInfoById(this.productInfo.farmingInfoId);
          if (farmingResponse && farmingResponse.code === 200) {
            this.farmingInfo = farmingResponse.data;
          }
        }

        // 获取加工信息
        if (this.productInfo.processingId) {
          const processingResponse = await productAPI.getProcessingInfo(this.productInfo.processingId);
          if (processingResponse && processingResponse.code === 200) {
            this.processingInfo = processingResponse.data;
          }
        }

        // 获取分销信息
        if (this.productInfo.batchNumber) {
          const distributionResponse = await distributionAPI.getDistributionInfoByBatchId(this.productInfo.batchNumber);
          if (distributionResponse && distributionResponse.code === 200) {
            this.distributionInfo = distributionResponse.data;
          }
        }
      } catch (error) {
        console.error('Failed to load detailed info:', error);
        this.$message.warning('部分详细信息加载失败');
      } finally {
        this.detailsLoading = false;
      }
    },

    // 打开扫码对话框
    scanQrCode() {
      this.scanDialogVisible = true;
      this.$nextTick(() => {
        this.initScanner();
      });
    },

    // 初始化扫码器
    initScanner() {
      // 注意：实际项目中需要集成二维码扫描库
      // 例如 Quagga.js, jsQR, qr-scanner 等

      // 这里为了示例，简单模拟扫码过程
      setTimeout(() => {
        this.scannerInitialized = true;
        // 模拟扫码成功，实际项目应该通过回调获取扫描结果
        setTimeout(() => {
          const mockTraceCode = 'TR' + Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
          this.traceCode = mockTraceCode;
          this.$message.success('扫码成功: ' + mockTraceCode);
          this.closeScanDialog();
          this.queryTrace();
        }, 3000);
      }, 1500);
    },

    // 关闭扫码对话框
    closeScanDialog() {
      this.scanDialogVisible = false;
      // 实际项目中应该停止摄像头和清理资源
      this.scannerInitialized = false;
    },

    // 重置查询 - 同时清除二维码
    resetQuery() {
      this.productInfo = null;
      this.farmingInfo = {};
      this.processingInfo = {};
      this.distributionInfo = {};
      this.traceCode = '';
      this.activeTab = 'basic';

      // 清除二维码相关数据
      this.qrCodeDataUrl = null;
      this.qrCodeGenerated = false;
      this.qrCodeInfo = null;
      localStorage.removeItem('lastQrCodeData');
    },

    // 分享产品
    shareProduct() {
      // 实际项目中应该集成分享功能
      const url = window.location.origin + this.$route.path + '?code=' + this.traceCode;

      try {
        // 尝试使用原生分享API
        if (navigator.share) {
          navigator.share({
            title: this.productInfo.productName,
            text: `查看${this.productInfo.productName}的溯源信息`,
            url: url
          });
        } else {
          // 复制链接到剪贴板
          this.copyToClipboard(url);
          this.$message.success('链接已复制到剪贴板，可以分享给好友了');
        }
      } catch (error) {
        console.error('Failed to share:', error);
        this.$message.error('分享失败');
      }
    },

    // 收藏产品
    favoriteProduct() {
      // 实际项目中应该调用收藏API
      this.$message.success('收藏成功');
    },

    // 复制到剪贴板
    copyToClipboard(text) {
      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
    },

    // 生成二维码
    generateQRCode() {
      console.log('生成二维码被点击, 当前溯源码:', this.traceCode);
      if (!this.traceCode) {
        this.$message.warning('请先输入溯源码');
        return;
      }

      // 如果已经生成过二维码且溯源码未变，直接显示
      if (this.qrCodeGenerated && this.qrCodeDataUrl) {
        console.log('二维码已存在，直接显示');
        return;
      }

      // 显示加载状态
      this.qrCodeLoading = true;

      setTimeout(async () => {
        try {
          // 创建完整的URL，包含域名和查询参数
          const completeUrl = `${window.location.origin}${this.$route.path}?code=${this.traceCode}`;

          // 查询产品基本信息，将信息直接放入二维码中
          try {
            const response = await traceQueryAPI.queryTrace(this.traceCode );
            if (response && response.code === 200) {
              const productData = response.data;

              // 创建包含基本溯源信息的文本
              let infoText = `【宁夏枸杞农产品溯源信息】\n`;
              infoText += `溯源码: ${this.traceCode}\n`;

              if (productData) {
                // 获取核心产品信息，注意确保数据存在
                const productName = productData.productName || '未知';
                const batchNumber = productData.batchNumber || '未知';
                const origin = productData.origin || '未知';
                const qualityLevel = productData.qualityLevel || '特级';
                const productionStandard = productData.productionStandard || 'GB/T 19330-2013';
                const sales = productData.orders.sales || '无';
                const contactInformation = productData.orders.customerPhone || '无';
                const locations = productData.orders.location || '无';
                const customerName = productData.orders.customerName || '无';
                const logisticsCompany = productData.distributionInfo.logisticsCompany || '无';
                const startLocation = productData.distributionInfo.startLocation || '无';
                const shipDate = productData.distributionInfo.shipDate || '无';
                const toLocation = productData.distributionInfo.toLocation || '无';
                const logisticsNumber = productData.distributionInfo.logisticsNumber || '无';

                infoText += `${productData.frequency}\n`;
                infoText += `产品名称: ${productName}\n`;
                infoText += `批次号: ${batchNumber}\n`;
                infoText += `产地: ${origin}\n`;
                infoText += `品质等级: ${qualityLevel}\n`;
                infoText += `生产标准: ${productionStandard}\n`;
                infoText += `自销/经销: ${sales}\n`;
                infoText += `联系方式: ${contactInformation}\n`;
                infoText += `商家地址: ${locations}\n`;
                infoText += `商家名称: ${customerName}\n`;
                infoText += `物流公司: ${logisticsCompany}\n`;
                infoText += `发货日期: ${shipDate}\n`;
                infoText += `收货地址: ${toLocation}\n`;
                infoText += `发货地址: ${startLocation}\n`;
                infoText += `物流订单: ${logisticsNumber}\n`;
                infoText += `扫描后若无法打开网页，请保存此信息\n`;
                infoText += `在线查询: ${completeUrl}`;
              } else {
                infoText += `未找到产品信息，请访问:\n${completeUrl}`;
              }

              console.log('生成二维码内容:', productData);
              // 保存二维码信息到组件状态
              this.qrCodeInfo = infoText;

              // 使用包含溯源信息的文本生成二维码
              QRCode.toDataURL(infoText, {
                errorCorrectionLevel: 'M', // 使用Medium级别的错误修正，提高容错性
                margin: 2,
                width: 220, // 增加宽度以容纳更多文本
                color: {
                  dark: '#303133',
                  light: '#ffffff'
                }
              }, (err, url) => {
                if (err) {
                  console.error('二维码生成失败:', err);
                  this.$message.error('二维码生成失败: ' + err.message);
                  this.qrCodeDataUrl = null;
                  this.qrCodeGenerated = false;
                } else {
                  console.log('二维码生成成功，数据URL长度:', url.length);
                  if (url && url.startsWith('data:image/png;base64,')) {
                    this.qrCodeDataUrl = url;
                    this.qrCodeGenerated = true;  // 标记二维码已生成
                    this.$message.success('二维码已生成，包含产品基本信息');

                    // 保存到本地存储以防页面刷新丢失
                    this.saveQrCodeToLocalStorage();
                  } else {
                    console.error('生成的数据URL格式不正确');
                    this.$message.error('二维码生成格式错误');
                    this.qrCodeDataUrl = null;
                    this.qrCodeGenerated = false;
                  }
                }
                this.qrCodeLoading = false;
              });

              return; // 成功生成带信息的二维码后返回
            }
          } catch (apiError) {
            console.error('获取产品信息失败:', apiError);
            // 如果获取信息失败，继续使用URL生成二维码
          }

          // 如果无法获取产品信息，退回到仅使用URL生成二维码
          QRCode.toDataURL(completeUrl, {
            errorCorrectionLevel: 'H',
            margin: 4,
            width: 180,
            color: {
              dark: '#303133',
              light: '#ffffff'
            }
          }, (err, url) => {
            if (err) {
              console.error('二维码生成失败:', err);
              this.$message.error('二维码生成失败: ' + err.message);
              this.qrCodeDataUrl = null;
              this.qrCodeGenerated = false;
            } else {
              console.log('二维码生成成功，数据URL长度:', url.length);
              if (url && url.startsWith('data:image/png;base64,')) {
                this.qrCodeDataUrl = url;
                this.qrCodeGenerated = true;  // 标记二维码已生成
                // 保存二维码URL信息
                this.qrCodeInfo = completeUrl;
                this.$message.success('二维码已生成，扫描后可直接查看溯源信息');

                // 保存到本地存储以防页面刷新丢失
                this.saveQrCodeToLocalStorage();
              } else {
                console.error('生成的数据URL格式不正确');
                this.$message.error('二维码生成格式错误');
                this.qrCodeDataUrl = null;
                this.qrCodeGenerated = false;
              }
            }
            this.qrCodeLoading = false;
          });
        } catch (error) {
          console.error('生成二维码过程中出错:', error);
          this.$message.error('生成二维码失败: ' + error.message);
          this.qrCodeDataUrl = null;
          this.qrCodeGenerated = false;
          this.qrCodeLoading = false;
        }
      }, 100); // 稍微延迟，确保视图已更新
    },

    // 保存二维码信息到本地存储
    saveQrCodeToLocalStorage() {
      try {
        // 保存溯源码和生成状态
        const qrData = {
          traceCode: this.traceCode,
          qrCodeInfo: this.qrCodeInfo,
          timestamp: new Date().getTime()
        };
        localStorage.setItem('lastQrCodeData', JSON.stringify(qrData));
        console.log('二维码信息已保存到本地存储');
      } catch (error) {
        console.error('保存二维码到本地存储失败:', error);
      }
    },

    // 从本地存储恢复二维码数据
    restoreQrCodeFromStorage() {
      try {
        const storedData = localStorage.getItem('lastQrCodeData');
        if (storedData) {
          const qrData = JSON.parse(storedData);

          // 检查是否是当前溯源码的二维码
          if (qrData.traceCode === this.traceCode) {
            console.log('从本地存储找到匹配的二维码数据');

            // 如果有存储的溯源码和信息，重新生成二维码
            if (qrData.qrCodeInfo) {
              this.qrCodeLoading = true;

              // 使用存储的信息重新生成二维码
              QRCode.toDataURL(qrData.qrCodeInfo, {
                errorCorrectionLevel: 'M',
                margin: 2,
                width: 220,
                color: {
                  dark: '#303133',
                  light: '#ffffff'
                }
              }, (err, url) => {
                if (!err && url) {
                  this.qrCodeDataUrl = url;
                  this.qrCodeGenerated = true;
                  this.qrCodeInfo = qrData.qrCodeInfo;
                  console.log('已从本地存储恢复二维码');
                }
                this.qrCodeLoading = false;
              });
            }
          }
        }
      } catch (error) {
        console.error('从本地存储恢复二维码失败:', error);
      }
    },

    // 下载二维码
    downloadQRCode() {
      if (!this.qrCodeDataUrl) {
        this.$message.warning('二维码尚未生成完成，请稍候');
        return;
      }

      try {
        // 创建下载链接
        const link = document.createElement('a');
        link.href = this.qrCodeDataUrl;

        // 使用溯源码作为文件名
        link.download = `溯源码_${this.traceCode}.png`;

        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success('二维码已下载');
      } catch (error) {
        console.error('下载二维码失败:', error);
        this.$message.error('下载二维码失败: ' + error.message);
      }
    }
  }
};
</script>

<style scoped>
.trace-query-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.trace-header {
  background-color: #f0f9eb;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 50px;
  margin-right: 15px;
}

.logo h1 {
  margin: 0;
  font-size: 20px;
  color: #67c23a;
}

.nav-links {
  display: flex;
  gap: 20px;
}

.nav-links a {
  color: #606266;
  text-decoration: none;
}

.nav-links a:hover {
  color: #67c23a;
}

.trace-content {
  flex: 1;
  padding: 40px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.query-box {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
  padding: 30px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.query-box h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
}

.query-desc {
  color: #606266;
  margin-bottom: 25px;
}

.query-input {
  margin-bottom: 20px;
}

.query-actions {
  margin-bottom: 30px;
}

.query-tips {
  text-align: left;
  color: #909399;
  font-size: 14px;
  margin-top: 30px;
}

.query-tips ul {
  padding-left: 20px;
}

.query-tips li {
  margin-bottom: 5px;
}

.product-info {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.product-header h2 {
  margin: 0;
}

.info-card {
  margin-bottom: 20px;
}

.product-image {
  width: 100%;
  text-align: center;
  margin-bottom: 20px;
}

.product-image img {
  max-width: 300px;
  max-height: 300px;
  border-radius: 4px;
}

.authenticity-seal {
  margin-top: 30px;
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.seal-icon {
  width: 40px;
  height: 40px;
  background-color: #67c23a;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  margin-right: 15px;
}

.seal-icon i {
  font-size: 20px;
}

.seal-text h4 {
  margin: 0 0 5px 0;
  color: #67c23a;
}

.seal-text p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.farm-images,
.processing-steps,
.logistics-track {
  margin-top: 30px;
}

.farm-images h4,
.processing-steps h4,
.logistics-track h4 {
  margin-bottom: 15px;
  border-left: 3px solid #67c23a;
  padding-left: 10px;
}

.image-grid {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.farm-image {
  width: calc(33.333% - 10px);
}

.farm-image .el-image {
  width: 100%;
  height: 0;
  padding-bottom: 75%;
  overflow: hidden;
  border-radius: 4px;
}

.image-caption {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

.share-box {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.share-box h4 {
  margin-bottom: 15px;
}

.share-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.trace-footer {
  background-color: #f5f7fa;
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.trace-footer p {
  margin: 5px 0;
}

.scan-box {
  text-align: center;
}

.scan-area {
  width: 200px;
  height: 200px;
  border: 2px dashed #dcdfe6;
  margin: 0 auto 15px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.scan-placeholder {
  color: #909399;
}

.scan-placeholder i {
  font-size: 24px;
  margin-bottom: 10px;
}

.scan-tip {
  text-align: center;
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

/* 二维码样式 */
.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.qr-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
  width: 260px;
  margin-bottom: 15px;
}

.qr-loading i {
  font-size: 36px;
  color: #409EFF;
  margin-bottom: 15px;
}

.qr-loading p {
  color: #606266;
  font-size: 14px;
}

.qr-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
  width: 260px;
  margin-bottom: 15px;
}

.qr-image {
  max-width: 260px;
  height: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.qr-error {
  width: 260px;
  height: 260px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px solid #f56c6c;
  border-radius: 4px;
  background-color: #fef0f0;
  color: #f56c6c;
}

.qr-error i {
  font-size: 40px;
  margin-bottom: 10px;
}

.qr-tip {
  color: #606266;
  font-size: 14px;
  margin: 10px 0;
  text-align: center;
}

.qr-actions {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .trace-content {
    padding: 20px;
  }

  .product-image img {
    max-width: 100%;
  }

  .farm-image {
    width: calc(50% - 7.5px);
  }

  .qr-canvas {
    max-width: 90%;
  }
}

/* 内联二维码样式 */
.qr-code-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  text-align: center;
}

.qr-code-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.qr-code-container-inline {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.qr-result-inline {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

/* 内联显示的二维码需要更明确的尺寸 */
.qr-result-inline .qr-image {
  width: 220px; /* 匹配生成的二维码宽度 */
  height: 220px;
  object-fit: contain;
}
</style>
